<template>
  <div class="app-container">
    <base-table
      ref="baseTable"
      :grid-options="gridOptions"
      @cell-click="handleViewOrUpdate"
      @cell-menu="cellContextMenuEvent"
      @menu-click="contextMenuClickEvent"
    >
      <template #toolbar>
        <el-button
          v-if="checkBtnPerms('add')"
          icon="el-icon-plus"
          type="primary"
          @click="handleAdd"
        >
          添加
        </el-button>
        <el-button
          v-if="checkBtnPerms('query')"
          icon="el-icon-search"
          type="primary"
          @click="handleQuery"
        >
          查询
        </el-button>
        <el-button
          v-if="checkBtnPerms('import')"
          icon="el-icon-upload2"
          type="primary"
          @click="handleImport"
        >
          导入
        </el-button>
        <el-button
          v-if="checkBtnPerms('download')"
          icon="el-icon-download"
          type="primary"
          @click="handleDownload"
        >
          下载附件
        </el-button>
        <el-button
          v-if="checkBtnPerms('delete')"
          icon="el-icon-remove"
          type="danger"
          @click="handleDelete"
        >
          删除
        </el-button>
      </template>
      <template #tools>
        <div style="margin-right: 12px;">
          <el-popover trigger="click" width="200">
            <div>
              <el-checkbox-group v-model="fixedLists" @change="onFixedChange">
                <template v-for="item in gridOptions.columns">
                  <el-checkbox
                    :key="item.field || item.type"
                    style="display: none;margin-bottom: 4px;"
                    :label="item.field || item.type"
                  >
                    {{ item.title }}
                  </el-checkbox>
                </template>
              </el-checkbox-group>
            </div>
            <button slot="reference" type="button" class="vxe-button type--button is--circle" title="固定列">
              <i class="el-icon-s-flag" />
            </button>
          </el-popover>
        </div>
      </template>
    </base-table>
    <ViewOrUpdate
      v-if="formModel && formKey"
      ref="viewOrUpdateDialog"
      :can-update="checkBtnPerms('update')"
      :fields="fields"
      :fixed-fields="fixedFields"
      :form-key="formKey"
      :form-model="formModel"
      @reload="handleReloadTable"
      @openReply="$refs.replyDrawer.open()"
    />
    <el-dialog :visible.sync="addDialogVisible" title="添加" width="60%">
      <biz-project-form
        v-if="formConfig.formKey"
        :key="formParseKey"
        :form-config="formConfig"
        @submit="submitForm"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">
          取 消
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="queryDialogVisible"
      class="t-dialog t-dialog--top"
      title="查询"
      width="50%"
    >
      <!-- <data-filter
        :fields="fields"
        @filter="
          (params) => {
            queryParams.filter = params;
          }
        "
      /> -->
      <data-filter
        :fields="fields"
        @filter="
          (params) => {
            tempFilter = params;
          }
        "
      />
      <div slot="footer" class="t-dialog__footer">
        <el-button @click="queryDialogVisible = false,resetQuery()">
          取 消
        </el-button>
        <el-button type="primary" @click="handleConditionQueryTable">
          查 询
        </el-button>
      </div>
    </el-dialog>
    <import ref="dataImport" :form-key="formKey" @success="handleReloadTable" />
    <reply-drawer
      ref="replyDrawer"
      :data-id="selectDataId"
      :form-key="formKey"
    />
    <download-file ref="downloadFile" :query-params="queryParams" />
  </div>
</template>

<script>
import BizProjectForm from "@/formgen/src/components/BizProjectForm"
import DataFilter from "./filter"
import ViewOrUpdate from "./ViewOrUpdate"
import BaseTable from "./BaseTable"
import ReplyDrawer from "./ReplyDrawer"
import DownloadFile from "./DownloadFile"
import {
  createFormResultRequest,
  deleteFormDataRequest,
  realTimeExport,
  listFormDataTableRequest
} from "@/api/project/data"
import {listFixedFormFieldsRequest, listFormFieldsRequest} from "@/api/project/form"
import _ from "lodash"
import Import from "./import"
import {formatTableColumn} from "./formatTableColumn"
import {Local} from "@/utils/storage"

export default {
  name: "FormData",
  components: {
    ReplyDrawer,
    BaseTable,
    Import,
    BizProjectForm,
    DataFilter,
    ViewOrUpdate,
    DownloadFile
  },
  props: {
    // 模式 1表示控制台中的管理 2 表示权限组
    mode: {
      type: Number,
      required: false,
      default: 1
    },
    // 权限信息
    authGroup: {
      type: Object,
      required: false
    }
  },
  data() {
    return {
      formKey: "",
      formConfig: {
        formKey: "",
        preview: false,
        showBtns: true
      },
      formParseKey: new Date().getTime(),
      formModel: {},
      gridOptions: {
        border: true,
        stripe: true,
        resizable: true,
        showHeaderOverflow: true,
        // showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "formDataGrid",
        rowId: "id",
        customConfig: {
          storage: true,
          checkMethod: this.checkColumnMethod
        },
        printConfig: {},
        menuConfig: {
          body: {
            options: [
              [
                {
                  code: "copy",
                  name: "复制内容",
                  prefixIcon: "fa fa-copy",
                  visible: true,
                  disabled: false
                },
                {
                  code: "clear",
                  name: "清除内容",
                  visible: true,
                  disabled: false
                }
              ],
              [
                {
                  code: "myPrint",
                  name: "打印",
                  prefixIcon: "fa fa-print",
                  visible: true,
                  disabled: false
                },
                {
                  code: "myExport",
                  name: "导出.csv",
                  prefixIcon: "fa fa-download",
                  visible: true,
                  disabled: false
                }
              ]
            ]
          }
        },
        sortConfig: {
          trigger: "cell",
          remote: true
        },
        filterConfig: {
          remote: true
        },
        pagerConfig: {
          pageSize: 10,
          pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000]
        },
        toolbarConfig: {
          refresh: true,
          import: false,
          export: false,
          print: false,
          zoom: true,
          custom: false,
          slots: {
            buttons: "toolbar_buttons",
            tools: "toolbar_tools"
          }
        },
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: "data.rows", // 配置响应结果列表字段
            total: "data.total" // 配置响应结果总页数字段
          },
          ajax: {
            // 接收 Promise 对象
            query: ({ page, sorts, filters, form }) => {
              this.queryParams.size = page.pageSize
              this.queryParams.current = page.currentPage - 1
              this.queryParams.formKey = this.formKey
              // A workaround for handle empty filter condition
              const filter = this.queryParams.filter
              if (filter.conditionList) {
                filter.conditionList = filter.conditionList.filter(({formItemId, method, value}) => {
                  return formItemId !== '' && method !== ''
                    && (value !== '' || method === 'IS_NULL' || method === 'NOT_NULL')
                })
              }
              return listFormDataTableRequest(this.queryParams).then((res) => {
                // field列res.data.rows行
                if(this.fields.length){
                  res.data.rows.forEach((row) =>{
                    for(var key in row){
                      if(key.indexOf('matrix_table')>-1){
                          this.fields.forEach((col) =>{
                            if(key == col.value){
                              row[key]=this.formatMatrixTableData(row[key],col)
                            }
                          })
                      }
                    }
                  })
                  return Promise.resolve(res)
                }else{
                  this.handleQueryFields().then(() => {
                      res.data.rows.forEach((row) =>{
                        for(var key in row){
                          if(key.indexOf('matrix_table')>-1){
                              this.fields.forEach((col) =>{
                                if(key == col.value){
                                  row[key]=this.formatMatrixTableData(row[key],col)
                                }
                              })
                          }
                        }
                      })
                  })
                  return Promise.resolve(res)
                }
                
              })
            },
            // 查询全部 导出全部时会被调用
            queryAll: () => {
              this.queryParams.size = null
              this.queryParams.current = null
              this.queryParams.formKey = this.formKey
              return listFormDataTableRequest(this.queryParams).then((res) => {
                // 临时处理对象导出显示
                let datas = []
                res.data.rows.forEach((data) => {
                  let dataObj = {}
                  _.keys(data).forEach((key) => {
                    if (_.isObject(data[key])) {
                      dataObj[key] = JSON.stringify(data[key])
                    } else {
                      dataObj[key] = data[key]
                    }
                  })
                  datas.push(dataObj)
                })
               
                return Promise.resolve(datas)
              })
            }
          }
        },
        columns: [],
        importConfig: {
          // remote: true,
          // importMethod: this.importMethod,
          types: ["csv", "html", "xml", "txt"],
          modes: ["insert"]
        },
        exportConfig: {
          remote: true,
          exportMethod: this.handleExport,
          types: ["xls"],//"xlsx", "csv"
          modes: ["all"]//"current", "selected", "all"
        },
        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true,
          
        }
      },
      queryDialogVisible: false,
      addDialogVisible: false,
      fields: [],
      fixedFields: [],
      fixedLists: [],
      queryParams: {
        authGroupId: null,
        formKey: "",
        filter: {}
      },
      tempFilter:{},
      // 选择数据Id
      selectDataId: null
    }
  },
  watch:{
    tempFilter: {
      handler: function (val) {
        console.log(this.tempFilter,'tempFilter')
        console.log(this.queryParams.filter,'this.queryParams.filter')
      },
      immediate: true,
      deep:true
    }
    
  },
  created() {
    this.formKey = this.$route.query.key || this.$route.params.key
    // 获取问卷字段并且初始化相关权限 修改删除等
    this.handleQueryFields().then((res) => {
      this.initPerms()
    })
    // 查询详情固定字段
    listFixedFormFieldsRequest(this.formKey).then((res) => {
      this.fixedFields = res.data
    })
  },
  mounted() { 
    // document.addEventListener('mouseup', e => {
    //   this.$nextTick(()=>{
    //     var  panels = document.getElementsByClassName('vxe-export--panel')
    //     console.log(panels,'panels11111111111----')

    //     var  panel = document.getElementsByClassName('vxe-export--panel')[0]
    //     console.log(panel,'panel2222222----')


    //     var trs = panel.getElementsByTagName('tbody')[0].getElementsByTagName('tr')
       
    //     console.log(trs,'trs')// 这两个获取dom的你用那个都行
    //     console.log()
    //     if (panel) {
          
          
    //     }
    //   }) 
    // })  
  },
  methods: {
    formatMatrixTableData(value, item) {
      if (!value) {
        return null
      }
      let data ={}
      Object.keys(value).forEach((key) => {
        console.log(item.scheme,'item.scheme')
        if(item.scheme){
          let row = item.scheme.table.rows.find((row) => row.id == key)
          if (row) {
            let rowValue = value[key]
            let colObj = {}
            Object.keys(rowValue).forEach((ckey) => {
              let col = item.scheme.table.columns.find((col) => col.id == ckey)
              if (col) {//多选[1,2]，单选[1]，上传等
                  colObj[col.label]=rowValue[ckey]
                  
              }
            })
            data[row.label]=colObj
          }
        }
      })
      console.log(data,'666666666666')
      return data
    },
    onFixedChange(values){
      this.gridOptions.columns = _.cloneDeep(this.gridOptions.columns).map((e) => {
        if (values.indexOf(e.field) > -1 || values.indexOf(e.type) > -1) {
          e.fixed = 'left'
        } else {
          e.fixed = ''
        }
        return e
      })
      const {key} = this.$route.query
      if (key) {
        Local.set(`fixed${key}`, values)
      }
    },
    /**
     * 检查按钮是否有权限
     * @param btn
     */
    checkBtnPerms(btn) {
      if (this.mode === 1) {
        return true
      }
      return this.authGroup.btnPerms.includes(btn)
    },
    checkColumnMethod ({ column }) {
      // if (['nickname', 'role'].includes(column.property)) {
        return false
      // }
      // return true
    },
    // 初始化权限
    initPerms() {
      // 管理模式
      if (this.mode === 1) {
        ["export", "print", "custom"].forEach((key) => {
          this.gridOptions.toolbarConfig[key] = true
        })
        return true
      }
      this.authGroup.btnPerms.forEach((key) => {
        this.gridOptions.toolbarConfig[key] = true
      })
      
      // 允许编辑的字段
      this.fields.forEach((field) => {
        let haveFieldIds = this.authGroup.fieldEditPerms
        // 没权限字段全部禁用
        if (!haveFieldIds.includes(field.value)) {
          if (field.scheme) {
            field.scheme.disabled = true
          }
        }
      })
    },
    resetQuery(){

    },
    handleConditionQueryTable() {
      this.queryParams.filter = JSON.parse(JSON.stringify(this.tempFilter))
      this.queryDialogVisible = false
      this.$refs.baseTable.getXGrid().commitProxy("reload")
    },
    handleQueryFields() {
      return new Promise((resolve, reject) => {
        if (this.mode === 1) {
          listFormFieldsRequest(this.formKey).then((res) => {
            this.handleTableColumns(res.data)
            resolve(this.fields)
          })
        } else {
          listFormFieldsRequest(this.formKey).then((res) => {
            let haveFieldIds = this.authGroup.fieldVisiblePerms
            this.fields = res.data.filter((item) =>
              haveFieldIds.includes(item.value)
            )
            this.handleTableColumns(this.fields)
            resolve(this.fields)
          })
          this.queryParams.authGroupId = this.authGroup.id
        }
      })
    },
    /**
     * 格式化处理表格数据
     */
    handleTableColumns(fields) {
      
      // 部分组件格式化显示 Json
      let firstCol = [{ type: "checkbox", width: 60 }]
      this.gridOptions.columns = firstCol.concat(
        fields.map((item) => {
          return formatTableColumn(item)
        })
      )
      console.log(fields,'fields000000000')
      // this.fields = [fields]
      this.fields = fields
      const {key} = this.$route.query
      if (key) {
        const values = Local.get(`fixed${key}`)
        if (values) {
          this.onFixedChange(values)
          this.fixedLists = [values]
        }
      }
    },
    handleQuery() {
      this.queryDialogVisible = true
    },
    handleImport() {
      this.$refs.dataImport.upload.open = true
    },
    handleExport({ options }) {
      console.log(options,'options')
      const { pager } = this.$refs.baseTable.getXGrid().getProxyInfo()
      let params = {
        columns: options.columns
          .reduce((arr, d) => {
            arr.push(d.property)
            return arr
          }, [])
          .filter((item) => item != null),
        filename: options.filename ? options.filename : this.$route.query.name,
        mode: options.mode,
        sheetName: options.sheetName,
        type: options.type,
        selectRecords: this.selectRecords,
        currentPage: pager.currentPage - 1,
        pageSize: pager.pageSize,
        total: pager.total,
        formKey: this.formKey,
        filter: this.queryParams.filter,
        authGroupId: this.authGroup?.id,
        checkboxIds: this.$refs.baseTable
          .getXGrid()
          .getCheckboxRecords()
          .map((item) => item.id)
      }
      this.$refs.baseTable.exportMsg()
      realTimeExport(params).then((res) => {
        var fileName = options.filename ? options.filename : this.$route.query.name
        let url = res.data
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', fileName + (options.type == "csv" ? '.csv' : '.xlsx'))
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) // 下载完成移除元素
        window.URL.revokeObjectURL(url) // 释放掉blob对象
        this.$refs.baseTable.endExportMsg()
      }).catch(() => {
        this.$refs.baseTable.endExportMsg()
      })
    },
    async handleDownload() {
      if (!this.$refs.baseTable.getXGrid().$data.tablePage.total) {
        this.$message.error("无附件，无法导出")
        return
      }
      this.$refs.downloadFile.openDownloadFile(this.formKey)
    },
    handleDelete() {
      let ids = this.$refs.baseTable
        .getXGrid()
        .getCheckboxRecords(true)
        .map((item) => item.id)
      if (!ids.length) {
        this.msgWarning("请选择数据")
        return
      }
      this.$confirm(
        `此操作将删除选中的${ids.length}条数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          deleteFormDataRequest(ids, this.formKey).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!"
            })
            this.$refs.baseTable.getXGrid().commitProxy("reload")
          })
        })
        .catch(() => {})
    },
    handleAdd() {
      this.formConfig.formKey = this.formKey
      this.formParseKey = new Date().getTime()
      this.addDialogVisible = true
    },
    handleReloadTable() {
      this.$refs.baseTable.getXGrid().commitProxy("reload")
    },
    cellContextMenuEvent({ row }) {
      const $grid = this.$refs.baseTable.getXGrid()
      $grid.setCurrentRow(row)
    },
    handleViewOrUpdate(event) {
      if (!this.checkBtnPerms("detail")) {
        return
      }
      if (event.triggerCheckbox) {
        return
      }
      this.formModel = event.row
      this.selectDataId = event.row.id
      this.$refs.viewOrUpdateDialog.showDialog()
    },
    contextMenuClickEvent({ menu, row, column }) {
      const $grid = this.$refs.baseTable.getXGrid()
      switch (menu.code) {
        case "copy":
          if (row && column) {
            if (this.$copyText(row[column.property])) {
              this.msgSuccess("已复制到剪贴板")
            }
          }
          break
        case "clear":
          $grid.clearData(row, column.property)
          break
        case "myPrint":
          $grid.print()
          break
        case "myExport":
          $grid.exportData()
          break
      }
    },
    submitForm(data) {
      createFormResultRequest({
        completeTime: 0,
        formKey: this.formConfig.formKey,
        submitOs: "",
        submitBrowser: "",
        submitUa: null,
        wxUserInfo: null,
        wxOpenId: "",
        accessTime:data.accessTime,
        originalData: data.formModel
      }).then(() => {
        setTimeout(() => {
          this.$refs.baseTable.getXGrid().commitProxy("reload")
        }, 1000)
        this.addDialogVisible = false
        this.msgSuccess("添加成功")
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  width: 100%;
}

::v-deep .project-form {
  background-color: #ffffff !important;
  width: 100% !important;
}

::v-deep .vxe-export--panel tr:last-child {
  display: none !important;
}

@media screen and (max-width: 500px) {
  ::v-deep .vxe-pager {
    padding-top: 30px !important;
  }
  ::v-deep .vxe-modal--box {
    width: 100% !important;
  }
  ::v-deep .el-dialog__wrapper .el-dialog {
    width: 100% !important;
  }
  ::v-deep .vxe-toolbar {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 10px;
    height: 100px;

    &:last-child .el-button {
      margin-left: 0px;
    }

    .vxe-toolbar {
      margin-top: 10px;
    }
  }
}
</style>
